<template>
  <div class="area-ranking-chart">
    <div class="page-header">
      <h3>区域展示</h3>
    </div>

    <div class="chart-container">
      <div ref="chartRef" id="areaChart"></div>
    </div>
  </div>
</template>

<script>
// 导入 ECharts 核心模块
import * as echarts from 'echarts/lib/echarts'

// 导入所需图表类型和组件
import 'echarts/lib/chart/bar'
import 'echarts/lib/chart/line'
import 'echarts/lib/component/tooltip'
import 'echarts/lib/component/title'
import 'echarts/lib/component/legend'
import 'echarts/lib/component/toolbox'
import 'echarts/lib/component/grid'

export default {
  name: 'AreaRankingChart',
  data() {
    return {
      areaData: [],
      loading: true,
      error: null,
      chartInstance: null
    }
  },
  mounted() {
    // 使用 nextTick 确保 DOM 已渲染
    this.$nextTick(() => {
      this.initChart()
      this.fetchAreaData()
    })

    // 监听窗口大小变化
    window.addEventListener('resize', this.resizeChart)
  },
  beforeDestroy() {
    // 清理资源
    window.removeEventListener('resize', this.resizeChart)
    if (this.chartInstance) {
      this.chartInstance.dispose()
      this.chartInstance = null
    }
  },
  methods: {
    initChart() {
      const chartDom = this.$refs.chartRef

      // 检查 DOM 元素是否存在
      if (!chartDom) {
        console.error('图表容器元素未找到')
        return
      }
      this.chartInstance = echarts.init(chartDom)
    },
    fetchAreaData() {
      this.loading = true

      this.$request({  url: 'queryQuYu',  method: 'get' })
          .then(response=> {
            if (response.data && Array.isArray(response.data)) {
              this.areaData = response.data
                  .filter(item => item.quyu) // 过滤quyu为空的记录
                  .map(item => ({
                    ...item,
                    loupanNum: item.loupanNum !== null ? item.loupanNum : 0,
                    fangyuanNum: item.fangyuanNum !== null ? item.fangyuanNum : 0
                  }))
            } else {
              // 处理非数组数据或空数据
              this.areaData = []
              console.warn('返回数据格式不正确或为空', response.data)
            }
            this.renderChart()
          })
          .catch(error => {
            this.error = error
            console.error('数据请求失败', error)
          })
          .finally(() => {
            this.loading = false
          })

    },

    renderChart() {
      if (!this.chartInstance || !this.areaData.length) return

      const xData = this.areaData.map(item => item.quyu)
      const buildingCount = this.areaData.map(item => item.loupanNum)
      const houseCount = this.areaData.map(item => item.fangyuanNum)

      const option = {
        title: {
          text: '区域统计',
          left: 'center',
          top: 10 // 调整标题位置
        },
        tooltip: { trigger: 'axis', axisPointer: { type: 'cross' } },
        legend: { data: ['楼盘数', '房源数'], top: 30 }, // 调整图例位置
        toolbox: { show: true, feature: { dataView: {}, restore: {}, saveAsImage: {} } },
        grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
        xAxis: { type: 'category', data: xData },
        yAxis: [
          {
            type: 'value',
            name: '楼盘数',
            position: 'left',
            min: 0,
            axisLabel: {
              formatter: value => value === 0 ? '0' : value
            }
          },
          {
            type: 'value',
            name: '房源数',
            position: 'right',
            min: 0,
            axisLabel: {
              formatter: value => value === 0 ? '0' : value
            }
          }
        ],
        series: [
          { name: '楼盘数', type: 'line', data: buildingCount, yAxisIndex: 0 },
          { name: '房源数', type: 'bar', data: houseCount, yAxisIndex: 1 }
        ]
      }

      this.chartInstance.setOption(option)
    },

    resizeChart() {
      this.chartInstance?.resize()
    }
  }
}
</script>

<style scoped>
.area-ranking-chart {
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  height: 100%;
}

.page-header {
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.chart-container {
  width: 100%;
  height: 400px;
}

#areaChart {
  width: 100%;
  height: 100%;
}
</style>